import { useContext } from "react"
import { PageContext } from "../../store"
import { componentsList } from "../../components"
import { cloneDeep } from 'lodash'
import { Select } from 'antd'

export const Config = () => {
  const { currentConfigId, list, setList } = useContext(PageContext)

  // console.log(currentConfigId, list)

  const renderConfigForm = ({
    type,
    value, // 
    onChange,
    options,
    defaultValue
  }) => {
    switch (type) {
      case 'input':
        return <input value={value || defaultValue} onChange={e => onChange(e.target.value)} />
      case 'inputNumber':
          return <input value={value || defaultValue} onChange={e => onChange(Number(e.target.value))} type="number" />
      case 'select': 
        return  <Select style={{width: '180px'}} value={value || defaultValue} onSelect={value => onChange(value)} options={options} />
      default:
        return <input value={value || defaultValue} onChange={e => onChange(e.target.value)} />
    }
  }

  const renderConfig = () => {
    if(currentConfigId) {
      // 从 list(设计区组件列表) 中找到 id = 当前选中组件ID, 获得当前选中组件数据
      const curComponent = list.find(item => item.id === currentConfigId)
      // 获取 当前选中组件数据的name
      const curComponentName = curComponent.name
      // 从 componentsList(组件库组件列表) 中找到 name = 当前选中组件的name, 获得当前选中组件对应的组件库组件数据
      const curComponentLib = componentsList.find(item => item.name === curComponentName)
      // 当前选中组件对应的组件库组件 支持的prop选项
      const libProp = curComponentLib.propsType
      // 当前组件的prop
      const curProp = curComponent.props
      // console.log({allProps, currentProp})

      const onChange = (value, name) => {
        const cloneList = cloneDeep(list)
        const target = cloneList.find(item => item.id === currentConfigId)
        target.props[name] = value
        setList(cloneList)
      }

      return (
        <div>
          <div>
            { libProp.map(item => { 
              return (
                <div key={item.name}>
                  <div>{item.label}</div>
                  <div>
                    {
                      renderConfigForm({
                        type: item.type,
                        value: curProp[item.name],
                        onChange: (value) => onChange(value, item.name),
                        options: item.options,
                        defaultValue: item.default
                      })
                    }
                  </div>
                </div>
              )
            })}
          </div>
        </div>
      )
    } else {
      return <div>请点击需要配置的组件</div>
    }
  }

  const renderStyle = () => {
    return <div>
      <div></div>
    </div>
  }

  return (
    <div style={{ width: "200px", padding: "5px" }}>
      <div>配置区</div>
      <div>
        {renderConfig()}
      </div>

      <div>样式区</div>
      <div>
        {renderStyle()}
      </div>
    </div>
  )
}
